<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" style="width: 80%;">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >

      <el-row :gutter="24">
        <el-col :span="8">
          <el-form-item label="试卷名称" prop="paperName">
            <el-input v-model="formData.paperName" placeholder="请输入试卷名称"/>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="考试时长" prop="duration">
            <el-input-number v-model="formData.duration" placeholder="输入（分钟）"/>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="试卷类型" prop="paperType">
            <el-select v-model="formData.paperType" placeholder="选择试卷类型" :disabled="formData.id>0">
              <el-option label="固定出题" value="0"/>
              <el-option label="随机试卷" value="1"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col v-if="formData.paperType === '1'" :span="4">
          <el-form-item label="随机方式" prop="randomType">
            <el-select v-model="formData.randomType" placeholder="选择随机方式">
              <el-option label="难度选题" value="0"/>
              <el-option label="知识点选题" value="1"/>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col style="padding-left: 110px" v-if="formData.paperType === '0'" :span="8">
          <el-button type="primary"
                     plain
                     @click="openQuestionBankForm()">
            <Icon icon="ep:plus" class="mr-5px"/>
            选择题目
          </el-button>
        </el-col>
        <el-col style="padding-left: 110px" v-if="formData.paperType === '1'" :span="8">
          <el-button type="primary"
                     plain
                     @click="openQuestionBankForm()">
            <Icon icon="ep:plus" class="mr-5px"/>
            选择题库
          </el-button>
        </el-col>
      </el-row>
      <div v-if="selectQuestionList.length>0 && formData.paperType === '0'">
        <!--- 固定出题---->
        <el-table :data="selectQuestionList" style="width: 100%" class='tables'>
          <el-table-column label="题库名称" align="center" prop="bankName">
            <template #default="scope">
              <el-tag v-if="scope.row.bankName!=null&&scope.row.bankName!=''">
                {{ scope.row.bankName }}
              </el-tag>
              <el-tag v-else>
                ----
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="题目文本" align="center" prop="questionText"/>
          <el-table-column label="题目类型" align="center" prop="questionType">
            <template #default="scope">
              <el-tag v-if="scope.row.questionType===1">
                单选
              </el-tag>
              <el-tag v-if="scope.row.questionType===2">
                多选
              </el-tag>
              <el-tag v-if="scope.row.questionType===3">
                判断
              </el-tag>
              <el-tag v-if="scope.row.questionType===4">
                填空
              </el-tag>
              <el-tag v-if="scope.row.questionType===5">
                简答
              </el-tag>
              <el-tag v-if="scope.row.questionType===6">
                问答
              </el-tag>
              <el-tag v-if="scope.row.questionType===7">
                计算
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="分值" align="center" prop="questionScore">
            <template #default="scope">
              <el-tag v-if="scope.row.questionType===1">
                {{ formData.singleChoiceScore }}分
              </el-tag>
              <el-tag v-if="scope.row.questionType===2">
                {{ formData.multipleChoiceFullScore }}分
              </el-tag>
              <el-tag v-if="scope.row.questionType===3">
                {{ formData.trueFalseScore }}分
              </el-tag>
              <el-tag v-if="scope.row.questionType===4">
                <el-input-number min="0" v-model="scope.row.questionScore"  @change="(event) => saveQuestionScore(event,scope.row)"/>
              </el-tag>
              <el-tag v-if="scope.row.questionType===5">
                <el-input-number min="0" v-model="scope.row.questionScore" @change="(event) => saveQuestionScore(event,scope.row)"/>
              </el-tag>
              <el-tag v-if="scope.row.questionType===6">
                <el-input-number min="0" v-model="scope.row.questionScore" @change="(event) => saveQuestionScore(event,scope.row)"/>
              </el-tag>
              <el-tag v-if="scope.row.questionType===7">
                <el-input-number min="0" v-model="scope.row.questionScore" @change="(event) => saveQuestionScore(event,scope.row)"/>
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="难度" align="center" prop="difficultyLevel">
            <template #default="scope">
              <el-tag v-if="scope.row.difficultyLevel===1">
                简单
              </el-tag>
              <el-tag v-if="scope.row.difficultyLevel===2">
                一般
              </el-tag>
              <el-tag v-if="scope.row.difficultyLevel===3">
                中等
              </el-tag>
              <el-tag v-if="scope.row.difficultyLevel===4">
                困难
              </el-tag>
              <el-tag v-if="scope.row.difficultyLevel===5">
                极难
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column
            label="创建时间"
            align="center"
            prop="createTime"
            :formatter="dateFormatter"
            width="180px"
          />
          <el-table-column label="Operations">
            <template #default="scope">
              <el-button
                size="small"
                type="danger"
                @click="handleDeleteSelect(scope.$index, scope.row)"
              >删除
              </el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <el-row :gutter="24">
          <div style="color: red;padding: 30px">
            <label style="font-size: large;padding-left: 20px">合计:</label>
            <el-tag v-if="formData.easyNum>0" style="color: red;margin-right: 20px;margin-left: 20px">
              简单：{{ formData.easyNum }}
            </el-tag>
            <el-tag v-if="formData.commonNum>0" style="color: red;margin-right: 20px">一般：{{ formData.commonNum }}</el-tag>
            <el-tag v-if="formData.mediumNum>0" style="color: red;margin-right: 20px">中等：{{ formData.mediumNum }}</el-tag>
            <el-tag v-if="formData.difficultNum>0" style="color: red;margin-right: 20px">困难：{{ formData.difficultNum }}</el-tag>
            <el-tag v-if="formData.extremelyDifficultNum>0" style="color: red;margin-right: 20px">极难：{{ formData.extremelyDifficultNum }}</el-tag>
          </div>
        </el-row>
        <el-row :gutter="24" v-if="formData.singleChoiceNum>0||formData.trueFalseNum>0">
          <el-col v-if="formData.singleChoiceNum>0" :span="10">
            <div >
              <el-form-item label="单选题分值" prop="singleChoiceScore">
                <el-input-number min="0"  v-model="formData.singleChoiceScore" placeholder="请输入单选题数量" @change="totalScore"/>

                <span style="margin-left: 20px;color: red">单选总分：{{ formData.singleChoiceNum}}题 * {{ formData.singleChoiceScore }}分={{ formData.singleChoiceNum*formData.singleChoiceScore }}分</span>
              </el-form-item>
            </div>
          </el-col>
          <el-col v-if="formData.trueFalseNum>0" :span="10">
            <div>
              <el-form-item label="判断题分值" prop="trueFalseScore">
                <el-input-number min="0" v-model="formData.trueFalseScore" placeholder="请输入判断题分值" @change="totalScore"/>
                <span style="margin-left: 20px;color: red">判断题总分：{{ formData.trueFalseNum}}题 * {{ formData.trueFalseScore }}分={{ formData.trueFalseNum*formData.trueFalseScore }}分</span>

              </el-form-item>
            </div>
          </el-col>
        </el-row>
        <el-row v-if="formData.multipleChoiceNum>0" :gutter="24">
          <el-col >
            <div>
              <el-form-item label="多选题分值" prop="multipleChoiceFullScore">
                <el-input-number min="0" v-model="formData.multipleChoiceFullScore"
                                 placeholder="请输入多选题分值" @change="totalScore"/>
                <span style="margin-left: 20px">漏选得分<el-input-number min="0" v-model="formData.multipleChoicePartialScore" placeholder="请输入漏选分值" /></span>
                <span style="margin-left: 20px;color: red">多选题总分：{{ formData.multipleChoiceNum}}题 * {{ formData.multipleChoiceFullScore }}分={{ formData.multipleChoiceNum*formData.multipleChoiceFullScore }}分</span>
              </el-form-item>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="24" v-if="formData.fillNum>0||formData.shortAnswerNum>0||formData.essayNum>0||formData.calculateNum>0">
          <el-col :span="6" v-if="formData.fillNum>0">
          <div>
            <el-form-item label="填空题总分" prop="fillTotalScore">
              <span style="margin-left: 20px;color: red">共：{{ formData.fillNum}}题 共{{ formData.fillTotalScore}}分</span>
            </el-form-item>
          </div>
          </el-col>
          <el-col :span="6" v-if="formData.shortAnswerNum>0">
            <div>
            <el-form-item label="简答题总分" prop="shortAnswerTotalScore">
              <span style="margin-left: 20px;color: red">共：{{ formData.shortAnswerNum}}题 共{{ formData.shortAnswerTotalScore}}分</span>
            </el-form-item>
            </div>
          </el-col>

          <el-col :span="6" v-if="formData.essayNum>0">
            <div>
            <el-form-item label="问答题总分" prop="essayTotalScore">
              <span style="margin-left: 20px;color: red">共：{{ formData.essayNum}}题 共{{ formData.essayTotalScore}}分</span>
            </el-form-item>
            </div>
          </el-col>
          <el-col :span="6" v-if="formData.calculateNum>0">
            <div>
            <el-form-item label="计算题总分" prop="calculateTotalScore">
              <span style="margin-left: 20px;color: red">共：{{ formData.calculateNum}}题 共{{ formData.calculateTotalScore}}分</span>
            </el-form-item>
            </div>
          </el-col>
        </el-row>
      </div>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="试卷总分" prop="totalScore">
            <el-input v-model="formData.totalScore" disabled/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="及格分数线" prop="passingScore">
            <el-input-number min="0" :max="passingScoreMax" v-model="formData.passingScore" placeholder="请输入及格线"/>
          </el-form-item>
        </el-col>
      </el-row>


    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
  <!-- 表单弹窗：添加/修改 -->
  <BankList ref="bankListFormRef" @success="getBankList"/>

  <!-- 表单弹窗：添加/修改 -->
  <QuestionList ref="quetionsListRef" @selectQuestions="receiveDataFromQuestionList"/>
</template>
<script setup lang="ts">
import {PaperApi, PaperVO} from '@/api/exam/paper'
import {reactive} from 'vue';
import BankList from './BankList.vue'
import QuestionList from './QuestionList.vue'
import {dateFormatter} from "@/utils/formatTime";

/** 试卷 表单 */
defineOptions({name: 'PaperForm'})

const {t} = useI18n() // 国际化
const message = useMessage() // 消息弹窗
function getBankList() {

}

const selectQuestionList = ref([])

function receiveDataFromQuestionList(data) {
  for (let i = 0; i < data.length; i++) {
    data[i].id=null;
  }
  selectQuestionList.value = data
  questionNumCount();
}
function saveQuestionScore(event,row){
  row.questionScore = event
  totalScore();
}
const passingScoreMax = ref(0)
function totalScore(){
  formData.value.singleChoiceTotalScore = selectQuestionList.value.filter(item => item.questionType === 1).length * formData.value.singleChoiceScore;
  selectQuestionList.value.filter(item => item.questionType === 1).forEach(item=>item.questionScore=formData.value.singleChoiceScore);
  formData.value.multipleChoiceTotalScore = selectQuestionList.value.filter(item => item.questionType === 2).length* formData.value.multipleChoiceFullScore;
  selectQuestionList.value.filter(item => item.questionType === 2).forEach(item=>item.questionScore=formData.value.multipleChoiceFullScore);
  formData.value.trueFalseTotalScore = selectQuestionList.value.filter(item => item.questionType === 3).length* formData.value.trueFalseScore;
  selectQuestionList.value.filter(item => item.questionType === 3).forEach(item=>item.questionScore=formData.value.trueFalseScore);
  formData.value.fillTotalScore = selectQuestionList.value.filter(item => item.questionType === 4).reduce((sum,item) => sum+Number(item.questionScore),0);
  formData.value.shortAnswerTotalScore = selectQuestionList.value.filter(item => item.questionType === 5).reduce((sum,item) => sum+Number(item.questionScore),0);
  formData.value.essayTotalScore = selectQuestionList.value.filter(item => item.questionType === 6).reduce((sum,item) => sum+Number(item.questionScore),0);
  formData.value.calculateTotalScore = selectQuestionList.value.filter(item => item.questionType === 7).reduce((sum,item) => sum+Number(item.questionScore),0);
  formData.value.totalScore = formData.value.singleChoiceTotalScore+formData.value.multipleChoiceTotalScore+formData.value.trueFalseTotalScore+formData.value.fillTotalScore+formData.value.shortAnswerTotalScore+formData.value.essayTotalScore+formData.value.calculateTotalScore;
  passingScoreMax.value = formData.value.totalScore
}
function questionNumCount() {
  formData.value.singleChoiceNum = selectQuestionList.value.filter(item => item.questionType === 1).length;
  formData.value.multipleChoiceNum = selectQuestionList.value.filter(item => item.questionType === 2).length;
  formData.value.trueFalseNum = selectQuestionList.value.filter(item => item.questionType === 3).length;
  formData.value.fillNum = selectQuestionList.value.filter(item => item.questionType === 4).length;
  formData.value.shortAnswerNum = selectQuestionList.value.filter(item => item.questionType === 5).length;
  formData.value.essayNum = selectQuestionList.value.filter(item => item.questionType === 6).length;
  formData.value.calculateNum = selectQuestionList.value.filter(item => item.questionType === 7).length;

  formData.value.easyNum = selectQuestionList.value.filter(item => item.difficultyLevel === 1).length;
  formData.value.commonNum = selectQuestionList.value.filter(item => item.difficultyLevel === 2).length;
  formData.value.mediumNum = selectQuestionList.value.filter(item => item.difficultyLevel === 3).length;
  formData.value.difficultNum = selectQuestionList.value.filter(item => item.difficultyLevel === 4).length;
  formData.value.extremelyDifficultNum = selectQuestionList.value.filter(item => item.difficultyLevel === 5).length;
  totalScore();
}

function handleDeleteSelect(index, row) {
  console.log(index)
  selectQuestionList.value.splice(index, 1);
  questionNumCount();
}

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  paperName: undefined,
  duration: undefined,
  paperType: '0',

  singleChoiceNum: 0,
  multipleChoiceNum: 0,
  trueFalseNum: 0,
  fillNum: 0,
  shortAnswerNum: 0,
  essayNum: 0,
  calculateNum: 0,

  singleChoiceScore: 0,
  multipleChoicePartialScore: 0,
  multipleChoiceFullScore: 0,
  trueFalseScore: 0,

  singleChoiceTotalScore: 0,
  multipleChoiceTotalScore: 0,
  trueFalseTotalScore: 0,
  fillTotalScore: 0,
  shortAnswerTotalScore: 0,
  essayTotalScore: 0,
  calculateTotalScore: 0,
  easyNum: 0,
  commonNum: 0,
  mediumNum: 0,
  difficultNum: 0,
  extremelyDifficultNum: 0,
  totalScore: 0,
  passingScore: 0,
  randomType: '0',
})
const formRules = reactive({
  paperName: [{required: true, message: '试卷名称不能为空', trigger: 'blur'}],
  duration: [{required: true, message: '考试时长（分钟）不能为空', trigger: 'blur'}],
  paperType: [{required: true, message: '试卷类型 1随机试卷 0固定出题不能为空', trigger: 'change'}],
  passingScore: [{required: true, message: '及格线不能为空', trigger: 'blur'}],
})

/** 添加/修改操作 */
const bankListFormRef = ref()
const quetionsListRef = ref()
const openQuestionBankForm = () => {
  if (formData.value.paperType === '0') {
    quetionsListRef.value.open(formData.value.paperName, formData.value.id)
  } else {
    bankListFormRef.value.open(formData.value.paperName, formData.value.id)
  }

}

const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await PaperApi.getPaper(id)
      formData.value.paperType = String(formData.value.paperType)
      passingScoreMax.value = formData.value.totalScore
      if(formData.value.paperType==='0'){
        selectQuestionList.value = formData.value.selectQuestionList
      }
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({open}) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as PaperVO

    if(formData.value.paperType==='0'){
      if(selectQuestionList.value.length===0){
        message.warning('选题不能为空');
        return;
      }
      if(formData.value.singleChoiceNum>0){
        if(formData.value.singleChoiceScore===0){
          message.warning('单选题分值不能为空');
          return;
        }
      }
      if(formData.value.trueFalseNum>0){
        if(formData.value.trueFalseScore===0){
          message.warning('判断题分值不能为空');
          return;
        }
      }
      if(formData.value.multipleChoiceNum>0){
        if(formData.value.multipleChoiceFullScore===0){
          message.warning('多选题分值不能为空');
          return;
        }
      }
      if(formData.value.fillNum>0){
        const num = selectQuestionList.value.filter(item => item.questionType === 4&&(item.questionScore===null||item.questionScore===0)).length;
        if(num>0){
          message.warning('填空题分值不能为空');
          return;
        }
      }
      if(formData.value.shortAnswerNum>0){
        const num = selectQuestionList.value.filter(item => item.questionType === 5&&(item.questionScore===null||item.questionScore===0)).length;5
        if(num>0){
          message.warning('简答题分值不能为空');
          return;
        }
      }
      if(formData.value.essayNum>0){
        const num = selectQuestionList.value.filter(item => item.questionType === 6&&(item.questionScore===null||item.questionScore===0)).length;
        if(num>0){
          message.warning('问答题分值不能为空');
          return;
        }
      }
      if(formData.value.calculateNum>0){
        const num = selectQuestionList.value.filter(item => item.questionType === 7&&(item.questionScore===null||item.questionScore===0)).length;
        if(num>0){
          message.warning('计算题分值不能为空');
          return;
        }
      }
      data.selectQuestionList=selectQuestionList.value
    }

    if (formType.value === 'create') {
      await PaperApi.createPaper(data)
      message.success(t('common.createSuccess'))
    } else {
      await PaperApi.updatePaper(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    paperName: undefined,
    duration: undefined,
    paperType: '0',

    singleChoiceNum: 0,
    multipleChoiceNum: 0,
    trueFalseNum: 0,
    fillNum: 0,
    shortAnswerNum: 0,
    essayNum: 0,
    calculateNum: 0,

    singleChoiceScore: 0,
    multipleChoicePartialScore: 0,
    multipleChoiceFullScore: 0,
    trueFalseScore: 0,

    singleChoiceTotalScore: 0,
    multipleChoiceTotalScore: 0,
    trueFalseTotalScore: 0,
    fillTotalScore: 0,
    shortAnswerTotalScore: 0,
    essayTotalScore: 0,
    calculateTotalScore: 0,
    easyNum: 0,
    commonNum: 0,
    mediumNum: 0,
    difficultNum: 0,
    extremelyDifficultNum: 0,
    easyTotalScore: 0,
    commonTotalScore: 0,
    mediumTotalScore: 0,
    difficultTotalScore: 0,
    extremelyDifficultTotalScore: 0,
    totalScore: 0,
    passingScore: 0,
    randomType: '0',
  }
  formRef.value?.resetFields()
}
onMounted(() => {

});
</script>
